﻿using System;
using System.Net;
using HtmlAgilityPack;
using LoLHQ.Properties;

namespace LoLHQ
{
    public delegate void DataReceivedHandler(object sender, LOLKingData data);

    class LOLKingLib
    {
        //public string Server = "na";

        public LOLKingData Data = null;

        public string Id { set; get; }

        public event DataReceivedHandler DataReceived;

        private bool resolve = true;

        private WebClient client = new WebClient();




        public LOLKingLib()
        {
            client.DownloadStringCompleted += client_DownloadStringCompleted;
        }

        public void GetDataAsync(string name)
        {
            resolve = true;
            client.CancelAsync();
            client.DownloadStringAsync(new Uri("http://www.lolking.net/search?name=" + name));
        }

        void client_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            // resolving summoner ID
            if (resolve)
            {
                Id = null;

                // get file
                HtmlDocument doc = new HtmlDocument();
                doc.LoadHtml(e.Result);

                // navigate to the parent results container
                HtmlNode parentNode = doc.DocumentNode.SelectSingleNode("/html/body/div[2]/div[2]/div[3]/div/div[2]/div[2]");
                foreach (HtmlNode node in parentNode.ChildNodes)
                {
                    // only analyze elements (skip text)
                    if (node.NodeType == HtmlNodeType.Element)
                    {
                        // this is our result box
                        HtmlNode target = node.ChildNodes[1];

                        // check if it contains useful information
                        if (target.GetAttributeValue("class", "search_result_item_disabled").CompareTo("search_result_item_disabled") == 0)
                            continue;

                        // get summoner ID
                        string summonerId = target.Attributes["onclick"].Value;
                        summonerId = summonerId.Substring(summonerId.IndexOf('\'') + 1);
                        summonerId = summonerId.Substring(0, summonerId.IndexOf('\''));
                        summonerId = summonerId.Replace("/summoner/", "");

                        // check if it's from correct server
                        if (summonerId.Contains(Settings.Default.Server))
                        {
                            // skip unranked
                            if (target.InnerText.Contains("No Rating"))
                                continue;

                            Id = summonerId;
                            break;
                        }
                    }
                }

                // user not found
                if (Id == null)
                {
                    DataReceived(this, null);
                }
                else // continue getting stats
                {
                    client.CancelAsync();
                    resolve = false;
                    client.DownloadStringAsync(new Uri("http://www.lolking.net/summoner/" + Id));
                }
            }
            else // ID resolved - now gather data
            {
                // get file
                HtmlDocument doc = new HtmlDocument();
                doc.LoadHtml(e.Result);

                LOLKingData data = new LOLKingData();

                string tmp;
                string[] split;
                
                tmp = doc.DocumentNode.SelectSingleNode("/html/body/div[2]/div[2]/div[3]/div/div[2]/div[2]/div").InnerText;
                data.Name = tmp;

                // general
                tmp = doc.DocumentNode.SelectSingleNode("/html/body/div[2]/div[2]/div[3]/div/div[3]/div/div[2]/div/div/ul/li[2]/div[3]").InnerText;
                // ignore everything else if a player is unraked
                if (tmp == "Unranked")
                {
                    DataReceived(this, null);
                    return;
                }
                data.TopRating = Int32.Parse(tmp);

                tmp = doc.DocumentNode.SelectSingleNode("/html/body/div[2]/div[2]/div[3]/div/div[3]/div/div[2]/div/div/ul/li[2]/div[6]/span").InnerText;
                data.Rating = Int32.Parse(tmp);

                tmp = doc.DocumentNode.SelectSingleNode("/html/body/div[2]/div[2]/div[3]/div/div[3]/div/div[2]/div/div/ul/li[2]/div[4]/span").InnerText;
                data.Wins = Int32.Parse(tmp);

                tmp = doc.DocumentNode.SelectSingleNode("/html/body/div[2]/div[2]/div[3]/div/div[3]/div/div[2]/div/div/ul/li[2]/div[5]/span").InnerText;
                data.Losses = Int32.Parse(tmp);

                tmp = doc.DocumentNode.SelectSingleNode("/html/body/div[2]/div[2]/div[3]/div/div[3]/div/div/div/div/div").InnerText;
                data.Change = Int32.Parse(tmp);


                // statistics
                tmp = doc.DocumentNode.SelectSingleNode("/html/body/div[2]/div[2]/div[3]/div/div[3]/div/div[2]/div[2]/div/div/table/tbody/tr/td[2]").InnerText;
                data.PentaKills = Int32.Parse(tmp, System.Globalization.NumberStyles.Any);

                tmp = doc.DocumentNode.SelectSingleNode("/html/body/div[2]/div[2]/div[3]/div/div[3]/div/div[2]/div[2]/div/div/table/tbody/tr[2]/td[2]").InnerText;
                data.QuadraKills = Int32.Parse(tmp, System.Globalization.NumberStyles.Any);

                tmp = doc.DocumentNode.SelectSingleNode("/html/body/div[2]/div[2]/div[3]/div/div[3]/div/div[2]/div[2]/div/div/table/tbody/tr[3]/td[2]").InnerText;
                data.TrippleKills = Int32.Parse(tmp, System.Globalization.NumberStyles.Any);

                tmp = doc.DocumentNode.SelectSingleNode("/html/body/div[2]/div[2]/div[3]/div/div[3]/div/div[2]/div[2]/div/div/table/tbody/tr[4]/td[2]").InnerText;
                data.DoubleKills = Int32.Parse(tmp, System.Globalization.NumberStyles.Any);

                tmp = doc.DocumentNode.SelectSingleNode("/html/body/div[2]/div[2]/div[3]/div/div[3]/div/div[2]/div[2]/div/div/table/tbody/tr[5]/td[2]").InnerText;
                data.Kills = Int32.Parse(tmp, System.Globalization.NumberStyles.Any);

                tmp = doc.DocumentNode.SelectSingleNode("/html/body/div[2]/div[2]/div[3]/div/div[3]/div/div[2]/div[2]/div/div/table/tbody/tr[6]/td[2]").InnerText;
                data.MostKills = Int32.Parse(tmp, System.Globalization.NumberStyles.Any);

                tmp = doc.DocumentNode.SelectSingleNode("/html/body/div[2]/div[2]/div[3]/div/div[3]/div/div[2]/div[2]/div/div/table/tbody/tr[7]/td[2]").InnerText;
                data.Assists = Int32.Parse(tmp, System.Globalization.NumberStyles.Any);

                tmp = doc.DocumentNode.SelectSingleNode("/html/body/div[2]/div[2]/div[3]/div/div[3]/div/div[2]/div[2]/div/div/table/tbody/tr[11]/td[2]").InnerText;
                data.LargestKillingSpree = Int32.Parse(tmp, System.Globalization.NumberStyles.Any);


                // LAST MATCHES
                // select match history container
                HtmlNodeCollection node = doc.DocumentNode.SelectNodes("//div[@class='match_details']");

                // enumerate every match
                foreach (HtmlNode child in node)
                {
                    if (child.NodeType != HtmlNodeType.Element)
                        continue;

                    HtmlNodeCollection targets = child.SelectNodes("./div[@class='match_details_cell']");

                    LastMatchStruct match = new LastMatchStruct();

                    // extract single game stats
                    tmp = targets[0].ChildNodes[1].InnerHtml;
                    tmp = tmp.Substring(tmp.IndexOf("=\"/champions/") + 13);
                    tmp = tmp.Substring(0, tmp.IndexOf("\">"));
                    tmp = char.ToUpper(tmp[0]) + tmp.Substring(1);
                    match.Champion = tmp;

                    tmp = targets[1].ChildNodes[1].InnerText;
                    tmp = tmp.Trim();
                    split = tmp.Split(new char[] { '\n' });
                    match.Kind = split[0].Trim();
                    match.Result = split[1].Trim();
                    match.When = split[2].Trim();

                    tmp = targets[2].ChildNodes[1].InnerText;
                    tmp = tmp.Replace("Game Length", "").Trim();
                    tmp = tmp.Replace("~", "");
                    match.Length = tmp;

                    tmp = targets[3].ChildNodes[1].InnerText;
                    tmp = tmp.Trim();
                    split = tmp.Split(new char[] { '\n' });
                    tmp = split[0].Replace("Kills", "").Trim();
                    match.KDA = tmp;
                    tmp = split[1].Replace("Deaths", "").Trim();
                    match.KDA = match.KDA + "/" + tmp;
                    tmp = split[2].Replace("Assists", "").Trim();
                    match.KDA = match.KDA + "/" + tmp;

                    tmp = targets[4].ChildNodes[1].InnerText;
                    tmp = tmp.Replace("Gold", "").Trim();
                    match.Gold = tmp;

                    tmp = targets[5].ChildNodes[1].InnerText;
                    tmp = tmp.Replace("Minions", "").Trim();
                    match.CS = tmp;

                    data.LastMatches.Add(match);
                }
                

                // RANKED STATS
                HtmlNode table = doc.DocumentNode.SelectSingleNode("//table[@id='ranked_stats']/tbody");

                // each row
                foreach (HtmlNode tr in table.ChildNodes)
                {
                    if (tr.NodeType != HtmlNodeType.Element)
                        continue;

                    RankedStatsStruct stats = new RankedStatsStruct();

                    tmp = tr.ChildNodes[1].GetAttributeValue("data-sortval", "");
                    stats.Champion = tmp;

                    tmp = tr.ChildNodes[3].GetAttributeValue("data-sortval", "");
                    stats.Wins = Int32.Parse(tmp, System.Globalization.NumberStyles.Any);

                    tmp = tr.ChildNodes[5].GetAttributeValue("data-sortval", "");
                    stats.Losses = Int32.Parse(tmp, System.Globalization.NumberStyles.Any);

                    tmp = tr.ChildNodes[7].GetAttributeValue("data-sortval", "");
                    stats.WinsP = Double.Parse(tmp, System.Globalization.NumberStyles.Any);

                    tmp = tr.ChildNodes[9].GetAttributeValue("data-sortval", "");
                    stats.Kills = Double.Parse(tmp, System.Globalization.NumberStyles.Any);

                    tmp = tr.ChildNodes[11].GetAttributeValue("data-sortval", "");
                    stats.Deaths = Double.Parse(tmp, System.Globalization.NumberStyles.Any);

                    tmp = tr.ChildNodes[13].GetAttributeValue("data-sortval", "");
                    stats.Assists = Double.Parse(tmp, System.Globalization.NumberStyles.Any);

                    tmp = tr.ChildNodes[15].GetAttributeValue("data-sortval", "");
                    stats.CS = Double.Parse(tmp, System.Globalization.NumberStyles.Any);

                    data.RankedStats.Add(stats);
                }

                DataReceived(this, data);
            }
        }


        
    }
}
